package com.chen.tankwar;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * Created by jijie.chen on 2017/11/9.
 */
public class TankClient extends Frame {

    int GAME_WIDTH = 800;
    int GAME_HEIGHT = 600;
    Image offScreenImage = null;

    private Tank myTank = new Tank(50, 50, Direction.STOP, this);

    private Missile missile = null;

    public Missile getMissile() {
        return missile;
    }

    public void setMissile(Missile missile) {
        this.missile = missile;
    }

    @Override
    public void paint(Graphics g) {
        myTank.draw(g);
        if (missile != null) {
            missile.draw(g);
        }
    }


    @Override
    public void update(Graphics g) {
        if (offScreenImage == null) {
            offScreenImage = this.createImage(GAME_WIDTH, GAME_HEIGHT);
        }
        Graphics gOffScreen = offScreenImage.getGraphics();
        Color c = gOffScreen.getColor();
        gOffScreen.setColor(new Color(0xcce8cf));
        gOffScreen.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
        gOffScreen.setColor(c);
        paint(gOffScreen);
        g.drawImage(offScreenImage, 0, 0, null);
    }


    public static void main(String[] args) {
        TankClient c = new TankClient();
        c.launchFrame();
    }

    private void launchFrame() {
        this.setSize(800, 600);
        this.setBackground(new Color(0xcce8cf));
        this.setLocation(0, 0);
        this.setVisible(true);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        this.setResizable(false);
        this.addKeyListener(new KeyMonitor());
        new Thread(new PaintThread()).start();
    }

    class PaintThread implements Runnable {
        @Override
        public void run() {
            while (true) {
                repaint();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    private class KeyMonitor extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {
            myTank.keyPressed(e);
        }

        @Override
        public void keyReleased(KeyEvent e) {
            myTank.keyReleased(e);
        }
    }
}